﻿using DeHeng_Mes.Business;
using DeHeng_Mes.Constant;
using DeHeng_Mes.Dao;
using DeHeng_Mes.Model.Data;
using DeHeng_Mes.Model.Table;
using DeHeng_Mes.Model;
using DeHeng_Mes.Utils;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using yingli_ningbo.Helpers;
using FluentFTP;
namespace DeHeng_Mes.Mapper
{
    public class DataCollector
    {
        private readonly OrderDao orderDao = new OrderDao();
        private readonly ProcessDao processDao = new ProcessDao();
        private readonly DeviceDao deviceDao = new DeviceDao();
        private readonly ErrorStatusDao errorStatusDao = new ErrorStatusDao();

        /// <summary>
        /// 采集螺柱焊的生产数据。
        /// </summary>
        /// <param name="code">追溯码，用于唯一标识工件。</param>
        /// <param name="line">工序编号，用于区分不同的工序。</param>
        /// <param name="date">日期，用于定位相关数据文件。</param>
        /// <param name="dataPointer">数据指针，用于标识获取数据的起始位置。</param>
        /// <param name="batchSize">用于指定数据插入批次大小</param>
        /// <param name="orderCode">工单号</param>
        public void CollectDataForStudWelding(DateTime date, string orderCode, string code = "", string line = "", int dataPointer = 0, int batchSize = 0)
        {
            Tools.ProduceLogText("螺柱焊采集中...");
            string originPath = SystemConstant.swOriginPath;
            string savePath = SystemConstant.swSavePath;
            string suffix = SystemConstant.swSuffix;
            List<string> savedFiles = new List<string>();
            List<TraceStudWeld> traceStudWeldList = new List<TraceStudWeld>();


            SharedFolderAccess.CopyCsvFilesWithSuffixAndDeleteAsync(originPath, savePath, suffix);
            savedFiles = CsvUtils.FindCsvFiles(savePath);
            if (savedFiles == null || savedFiles.Count == 0)
            {
                Tools.ProduceLogText("未找到螺柱焊文件。");
                errorStatusDao.InsertSaveFailed(ProcessConstant.StudWelding, code);
            }
            else
            {
                foreach (var savedFile in savedFiles)
                {
                    try
                    {
                        // 假设你有一个名为 YourRecordType 的类来映射 CSV 文件的每一行
                        List<StudWeld> records = CsvUtils.ReadCsvFile<StudWeld>(savedFile, ";");
                        if (records != null && records.Count > 0)
                        {
                            foreach (var record in records)
                            {
                                if (record.traceNo == code)
                                {
                                    var traceStudWeld = new TraceStudWeld
                                    {
                                        TraceId = code,
                                        OrderCode = orderCode,
                                        WeldNo = record.weldNo,
                                        EquipmentNumber = record.equipmentNumber,
                                        Output = record.output,
                                        ProgramNumber = record.programNumber,
                                        WeldingTimeUpperLimit = record.weldingTimeUpperLimit,
                                        WeldingTimeLowerLimit = record.weldingTimeLowerLimit,
                                        WeldingTimeSetting = record.weldingTimeSetting,
                                        WeldingVoltageUpperLimit = record.weldingVoltageUpperLimit,
                                        WeldingVoltageLowerLimit = record.weldingVoltageLowerLimit,
                                        WeldingVoltageSetting = record.weldingVoltageSetting,
                                        ArcVoltageUpperLimit = record.arcVoltageUpperLimit,
                                        ArcVoltageLowerLimit = record.arcVoltageLowerLimit,
                                        ArcVoltageSetting = record.arcVoltageSetting,
                                        LiftingHeightUpperLimit = record.liftingHeightUpperLimit,
                                        LiftingHeightLowerLimit = record.liftingHeightLowerLimit,
                                        LiftingHeightSetting = record.liftingHeightSetting,
                                        MoltenPoolInsertionTimeUpperLimit = record.moltenPoolInsertionTimeUpperLimit,
                                        MoltenPoolInsertionTimeLowerLimit = record.moltenPoolInsertionTimeLowerLimit,
                                        MoltenPoolInsertionTimeSetting = record.moltenPoolInsertionTimeSetting,
                                        ImmersionPointUpperLimit = record.immersionPointUpperLimit,
                                        ImmersionPointLowerLimit = record.immersionPointLowerLimit,
                                        ImmersionPointSetting = record.immersionPointSetting,
                                        result = record.result,
                                    };
                                    var properties = typeof(TraceStudWeld).GetProperties();
                                    for (int i = 1; i <= 16; i++)
                                    {
                                        var currentProp = properties.FirstOrDefault(p => p.Name == $"Current{i}");
                                        var timeProp = properties.FirstOrDefault(p => p.Name == $"Time{i}");
                                        var pulsesProp = properties.FirstOrDefault(p => p.Name == $"NumberOfPulses{i}");

                                        if (currentProp != null) currentProp.SetValue(traceStudWeld, record.GetType().GetProperty($"current{i}").GetValue(record));
                                        if (timeProp != null) timeProp.SetValue(traceStudWeld, record.GetType().GetProperty($"time{i}").GetValue(record));
                                        if (pulsesProp != null) pulsesProp.SetValue(traceStudWeld, record.GetType().GetProperty($"numberOfPulses{i}").GetValue(record));
                                    }

                                    traceStudWeldList.Add(traceStudWeld);
                                }
                            }
                            if (traceStudWeldList.Count > 0)
                            {
                                try
                                {
                                    processDao.InsertStudWeldData(traceStudWeldList);
                                }
                                catch (Exception ex)
                                {
                                    Tools.ProduceLogTextError($"处理螺柱焊文件 {savedFile} 时发生错误: {ex.Message}");
                                    errorStatusDao.InsertSaveFailed(ProcessConstant.StudWelding, code);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Tools.ProduceLogTextError($"处理螺柱焊文件 {savedFile} 时发生错误: {ex.Message}");
                        errorStatusDao.InsertSaveFailed(ProcessConstant.StudWelding, code);
                    }
                }
            }
        }

        /// <summary>
        /// 采集 FDS 数据并插入数据库。
        /// 该方法读取指定路径下的 JSON 文件，解析文件内容生成追溯数据并存储到数据库。
        /// </summary>
        /// <param name="code">追溯码，用于匹配记录。</param>
        /// <param name="line">产线编号，用于验证是否为空。</param>
        /// <param name="date">指定的日期（未使用）。</param>
        /// <param name="dataPointer">数据指针（未使用）。</param>
        /// <param name="batchSize">数据指针（未使用）。</param>
        /// <param name="orderCode">订单号</param>
        public void CollectDataForFds(DateTime date, string orderCode ,string code = "", string line = "", int dataPointer = 0, int batchSize = 0)
        {
            List<TraceFds> traceFds = new List<TraceFds>();
            int i = 0;
            try
            {
                List<FDSResult> fDSResults = processDao.GetFdsResultData(code, line);
                var traceFdsList = fDSResults.ConvertAll<TraceFds>(
                fdsResult => new TraceFds
                {
                    Id = fdsResult.Id,
                    TraceId = fdsResult.TraceId,
                    ProgName = fdsResult.ProgName,
                    Index = fdsResult.Index,
                    Station = fdsResult.Station,
                    Result = fdsResult.Result,
                    StartTime = fdsResult.StartTime,
                    Duration = fdsResult.Duration,
                    ProgStepCount = fdsResult.ProgStepCount,
                });
                List<FDSSingleResults> fDSSingleResults = processDao.GetFdsSingleResultData(fDSResults);
                foreach (var item in traceFdsList)
                {
                    item.Type = fDSSingleResults[i].Type;
                    item.Step = fDSSingleResults[i].Step;
                    item.Value = fDSSingleResults[i].Value;
                    i++;
                }
                List<FDSStepResults> fDSStepResults = processDao.GetFdsStepResultData(fDSResults);
                string TorqueRecord = "";
                string AngleRecord = "";
                string ADepthRecord = "";

                for (int k = 0; k < traceFdsList.Count; k++)
                {
                    for (int j = 0; j < int.Parse(traceFdsList[0].ProgStepCount); j++)
                    {
                        if (fDSStepResults[j].Name.Equals("Torque"))
                            TorqueRecord = fDSStepResults[j].Parameter;
                        if (fDSStepResults[j].Name.Equals("Angle"))
                            TorqueRecord = fDSStepResults[j].Parameter;
                        if (fDSStepResults[j].Name.Equals("ADepth"))
                            ADepthRecord = fDSStepResults[j].Parameter;
                        switch (j)
                        {
                            case 0:
                                traceFdsList[k].Torque1 = TorqueRecord;
                                traceFdsList[k].Angle1 = AngleRecord;
                                traceFdsList[k].Depth1 = ADepthRecord;
                                break;
                            case 1:
                                traceFdsList[k].Torque2 = TorqueRecord;
                                traceFdsList[k].Angle2 = AngleRecord;
                                traceFdsList[k].Depth2 = ADepthRecord;
                                break;
                            case 2:
                                traceFdsList[k].Torque2 = TorqueRecord;
                                traceFdsList[k].Angle2 = AngleRecord;
                                traceFdsList[k].Depth2 = ADepthRecord;
                                break;
                            case 3:
                                traceFdsList[k].Torque2 = TorqueRecord;
                                traceFdsList[k].Angle2 = AngleRecord;
                                traceFdsList[k].Depth2 = ADepthRecord;
                                break;
                            case 4:
                                traceFdsList[k].Torque2 = TorqueRecord;
                                traceFdsList[k].Angle2 = AngleRecord;
                                traceFdsList[k].Depth2 = ADepthRecord;
                                break;
                        }
                    }
                }

                if (traceFdsList.Count > 0)
                {
                    processDao.InsertFdsDataList(traceFdsList);
                }
                else
                {
                    errorStatusDao.InsertSaveFailed(ProcessConstant.Fds, code);
                    Tools.ProduceLogTextError($"Fds数据未生成, 追溯码为{code}");
                }
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"处理Fds文件时出现错误: {ex.Message}");
                errorStatusDao.InsertSaveFailed(ProcessConstant.Fds, code);
            }

            Tools.ProduceLogText("Fds采集完成。");
        }

        /// <summary>
        /// 采集涂胶的生产数据。
        /// </summary>
        /// <param name="code">追溯码，用于唯一标识工件。</param>
        /// <param name="line">生产线编号，用于区分左、右及小工位。</param>
        /// <param name="date">日期，用于定位相关数据文件。</param>
        /// <param name="dataPointer">数据指针，可能用于标识数据的具体位置（尚未使用）。</param>
        /// <param name="batchSize"></param>
        /// <param name="orderCode">订单号</param>
        public void CollectDataForGluing(DateTime date, string orderCode, string code = "", string line = "", int dataPointer = 0, int BatchSize = 0)
        {
            FtpClient client = new FtpClient();

            FtpHelper ftpHelper;

            try
            {
                if (line == "")
                {
                    errorStatusDao.InsertSaveFailed(ProcessConstant.Glue, code, line);
                    return;
                }
                string loadPath = string.Empty;
                string copyPath = string.Empty;
                string station = string.Empty;
                FtpListItem[] items;
                TimeSpan generatedTime = deviceDao.getTimeByTraceCode(code);

                if (line.Contains("left"))
                {
                    copyPath = SystemConstant.leftGlueCopyPath;
                    loadPath = SystemConstant.leftGlueLoadPath;
                    station = "left";
                    ftpHelper = new FtpHelper(client, "192.168.5.241", false, "m2iftp", "yq123456");
                    client.Connect();
                    items = client.GetListing(loadPath);
                }
                else if (line.Contains("right"))
                {
                    copyPath = SystemConstant.rightGlueCopyPath;
                    loadPath = SystemConstant.rightGlueLoadPath;
                    station = "right";
                    ftpHelper = new FtpHelper(client, "192.168.6.241", false, "m2iftp", "yq123456");
                    client.Connect();
                    items = client.GetListing(loadPath);
                }
                else
                {
                    copyPath = SystemConstant.smallGlueCopyPath;
                    loadPath = SystemConstant.smallGlueLoadPath;
                    station = "small";
                    ftpHelper = new FtpHelper(client, "192.168.7.242", false, "m2iftp", "yq123456");
                    client.Connect();
                    items = client.GetListing(loadPath);
                }

                if (items == null)
                {
                    errorStatusDao.InsertSaveFailed(ProcessConstant.Glue, code, line);
                    return;
                }
                Tools.ProduceLogText("涂胶采集中...");
                // 获取根目录下的文件和文件夹列表
                string operateTime = date.ToString("yyyy-MM-dd");
                string todayString = DateTime.Now.ToString("yyyy-MM-dd");

                if (!operateTime.Equals(todayString))
                {
                    todayString = operateTime;
                }

                // 筛选包含指定字段的文件
                var matchingFileList = items
                    .Where(item => item.Type == FtpObjectType.File && item.Name.Contains(todayString))
                    .ToList();
                if (matchingFileList.Count > 0)
                {
                    // 检查本地路径是否存在，如果不存在则创建
                    if (!Directory.Exists(copyPath))
                    {
                        Directory.CreateDirectory(copyPath);
                    }
                    foreach (var file in matchingFileList)
                    {
                        string localFilePath = Path.Combine(copyPath, file.Name);
                        // 下载文件到本地
                        var status = client.DownloadFile(localFilePath, file.FullName, FtpLocalExists.Overwrite, FtpVerify.Retry);
                        if (status == FtpStatus.Success)
                        {
                            Tools.DeviceLogText($"下载涂胶CSV文件 {file.Name} 成功,完整文件路径为：{localFilePath}。");
                            List<Glue> records = CsvUtils.ReadCsvFile<Glue>(localFilePath, ",", false);
                            if (records != null && records.Count > 0)
                            {
                                Glue record = records.Last(); // 或 records[records.Count - 1];
                                string defaultTime = "1900-01-01 00:00:00";
                                var traceGlue = new TraceGlue
                                {
                                    TraceId = code,
                                    OrderCode = orderCode,
                                    OperationId = station,
                                    CoatingSpeed = (record.CostTime.HasValue && record.GlueFlowRate.HasValue && record.CostTime.Value != 0) ? ((record.GlueFlowRate.Value / record.CostTime.Value)).ToString() : "N/A",
                                    CoatingFlowRate = record.GlueFlowRate.ToString(),
                                    CoatingPressure = (record.MinPressure.HasValue && record.MaxPressure.HasValue) ? ((record.MinPressure + record.MaxPressure) / 2).ToString() : "N/A",
                                    CoatingTemperature = record.GlueGunTemperature.ToString(),
                                    CoatingTime = record.CostTime.ToString(),
                                    StartTime = DateTime.ParseExact($"{record.Date.ToString("yyyy-MM-dd")} {record.SystemStartTime}", "yyyy-MM-dd HHmmss", null),
                                    EndTime = (record.SystemEndTime.Equals("0"))
                                    ? DateTime.Parse(defaultTime)
                                    : DateTime.ParseExact($"{record.Date.ToString("yyyy-MM-dd")} {record.SystemEndTime}", "yyyy-MM-dd HHmmss", null)
                                };
                                try
                                {
                                    processDao.InsertGlueData(traceGlue);
                                    errorStatusDao.DeleteSaveFailed(ProcessConstant.Glue, code, line);

                                }
                                catch (Exception ex)
                                {
                                    Tools.ProduceLogTextError($"处理涂胶文件 {localFilePath} 时发生错误: {ex.Message}");
                                    errorStatusDao.InsertSaveFailed(ProcessConstant.Glue, code, line);
                                }
                            }
                            else
                            {
                                Tools.DeviceLogText($"下载涂胶文件 {file.Name} 失败: {file.FullName},服务器为{client.Host}");
                                errorStatusDao.InsertSaveFailed(ProcessConstant.Glue, code, line);
                            }
                        }
                        else
                        {
                            Tools.DeviceLogText($"下载涂胶文件 {file.Name} 失败: {file.FullName},服务器为{client.Host}");
                            errorStatusDao.InsertSaveFailed(ProcessConstant.Glue, code, line);
                        }
                    }
                    Tools.ProduceLogText("涂胶采集结束");
                }
                else
                {
                    Tools.ProduceLogTextError($"服务器为{client.Host}读取涂胶CSV文件失败：未生成文件");
                    errorStatusDao.InsertSaveFailed(ProcessConstant.Glue, code, line);
                }
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"服务器为{client.Host}读取涂胶CSV文件失败：" + ex.Message);
                errorStatusDao.InsertSaveFailed(ProcessConstant.Glue, code, line);
            }
            finally
            {
                // 确保无论发生什么情况都能断开连接
                if (client.IsConnected)
                {
                    client.Disconnect();
                }
            }
        }

        /// <summary>
        /// 根据路径 文件名 模糊查找SPR-CSV文件并读取保存至数据库
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="vagueName">模糊查找文本</param>
        /// <param name="newVin">新的条码</param>
        /// <param name="reBoot">机器人编号</param>
        /// <param name="orderCode">订单号</param>
        /// <param name="processName">工序名</param>
        public void CollectDataForSpr(DateTime date,string orderCode, String vagueName, string processName, int dataPointer = 0, int BatchSize = 0)
        {
            try
            {
                //查找文件 并返回 文件绝对路径

                string path = "";
                string reBoot = "" ; 
                List<String> filesPath = FileFinderHelper.FindFilesByNameAsync(path, vagueName);
                if (filesPath == null || filesPath.Count <= 0)
                {
                    errorStatusDao.InsertSaveFailed(ProcessConstant.Spr, vagueName, processName);
                    //throw new Exception($"通过条码[{vagueName}]未找到对应的SPR-CSV文件");
                    return;
                }
                
                //创建一个实体集合
                List<TraceSpr> sprList = new List<TraceSpr>();

                foreach (var file in filesPath)
                {

                    //读取文件并返回所有 行
                    String[] lines = System.IO.File.ReadAllLines(@file, System.Text.Encoding.Default);
                    if (lines == null || lines.Length <= 0)
                    {
                        errorStatusDao.InsertSaveFailed(ProcessConstant.Spr, vagueName, processName);
                        //throw new Exception($"读取文件[{@file}]失败,(未找到该文件)");
                        return;
                    }

                    TraceSpr spr = new TraceSpr();
                    spr.SaveTime = DateTime.Now;
                    spr.TraceId = vagueName;
                    spr.OrderCode = orderCode;

                    //读取文件第2行  从文件名中提取信息
                    String[] row2 = lines[1].Split(',');
                    String[] row2Array = row2[1].Split('_');
                    spr.Name = row2Array[0];
                    spr.OperationCode = row2Array[1];
                    spr.RivetNumber = row2Array[4];
                    spr.RivetDate = Tools.ParseCustomDateTime(row2Array[3]).ToString("yyyy-MM-dd HH:mm:ss");
                    spr.Result = row2Array[6];

                    //读取文件第323行  从文件名中提取信息
                    String[] row323 = lines[323].Split(',');
                    spr.CurveData = row323[1];

                    //读取文件第242行  从文件名中提取信息
                    String[] row242 = lines[242].Split(',');
                    String[] row242Array0 = row242[0].Split(new char[2] { ':', '$' });
                    spr.XMax_X_Set1 = row242Array0[1];
                    spr.XMin_X_Set1 = row242Array0[3];

                    //读取文件第272行  从文件名中提取信息
                    String[] row272 = lines[272].Split(',');
                    String[] row272Array0 = row272[0].Split(new char[2] { ':', '}' });
                    spr.Value_X_Actual1 = row272Array0[2];


                    String[] row242Array1 = row242[1].Split(new char[2] { ':', '$' });
                    spr.XMax_Y_Set1 = row242Array1[1];
                    spr.XMin_Y_Set1 = row242Array1[3];
                    String[] row272Array1 = row272[1].Split(new char[2] { ':', '$' });
                    spr.Value_Y_Actual1 = row272Array1[2];

                    String[] row242Array2 = row242[2].Split(new char[2] { ':', '$' });
                    spr.XMax_X_Set2 = row242Array2[1];
                    spr.XMin_X_Set2 = row242Array2[3];
                    String[] row272Array2 = row272[2].Split(new char[2] { ':', '}' });
                    spr.Value_X_Actual2 = row272Array2[2];

                    String[] row242Array3 = row242[3].Split(new char[2] { ':', '$' });
                    spr.XMax_Y_Set2 = row242Array3[1];
                    spr.XMin_Y_Set2 = row242Array3[3];
                    String[] row272Array3 = row272[3].Split(new char[2] { ':', '}' });
                    spr.Value_Y_Actual2 = row272Array3[2];

                    String[] row242Array4 = row242[4].Split(new char[2] { ':', '$' });
                    spr.XMax_X_Set3 = row242Array4[1];
                    spr.XMax_X_Set3 = row242Array4[3];
                    String[] row272Array4 = row272[4].Split(new char[2] { ':', '}' });
                    spr.Value_X_Actual3 = row272Array4[2];

                    String[] row242Array5 = row242[5].Split(new char[2] { ':', '$' });
                    spr.XMax_Y_Set3 = row242Array5[1];
                    spr.XMin_Y_Set3 = row242Array5[3];
                    String[] row272Array5 = row272[5].Split(new char[2] { ':', '}' });
                    spr.Value_Y_Actual3 = row272Array5[2];

                    String[] row242Array6 = row242[6].Split(new char[2] { ':', '$' });
                    spr.XMax_X_Set4 = row242Array6[1];
                    spr.XMin_X_Set4 = row242Array6[3];
                    String[] row272Array6 = row272[6].Split(new char[2] { ':', '}' });
                    spr.Value_X_Actual4 = row272Array6[2];

                    String[] row242Array7 = row242[7].Split(new char[2] { ':', '$' });
                    spr.XMax_Y_Set4 = row242Array7[1];
                    spr.XMin_Y_Set4 = row242Array7[3];
                    String[] row272Array7 = row272[7].Split(new char[2] { ':', '}' });
                    spr.Value_Y_Actual4 = row272Array7[2];

                    spr.RivetProgramNum = "0";
                    spr.Program = "0";
                    spr.State = "0";
                    spr.RobotCode = reBoot;
                    spr.XMax_X_Set5 = "0";
                    spr.XMin_X_Set5 = "0";
                    spr.Value_X_Actual5 = "0";
                    spr.XMax_Y_Set5 = "0";
                    spr.XMin_Y_Set5 = "0";
                    spr.Value_Y_Actual5 = "0";
                    spr.User1 = "-";
                    spr.User2 = "-";
                    spr.User3 = "-";
                    spr.User4 = "-";
                    spr.User5 = "-";
                    spr.Reserve1 = "-";
                    spr.Reserve2 = "-";
                    spr.Reserve3 = "-";
                    spr.Reserve4 = "-";
                    spr.Reserve5 = "-";

                    sprList.Add(spr);
                }
                if (sprList.Count > 0)
                {
                    processDao.InsertSprData(sprList);
                }
                else
                {
                    Tools.ProduceLogTextError($"追溯码{vagueName}采集SPR数据失败, 原因为: 数据未生成");
                    errorStatusDao.InsertSaveFailed(ProcessConstant.Spr, vagueName, processName);
                }
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"追溯码{vagueName}采集SPR数据失败, 原因为: {ex.Message}");
                errorStatusDao.InsertSaveFailed(ProcessConstant.Spr, vagueName, processName);
            }
        }
        #region 内部方法

        /// <summary>
        /// 根据目标字符串在根路径及其子文件夹中搜索包含目标字符串的 JSON 文件路径。
        /// </summary>
        /// <param name="rootPath">根目录路径。</param>
        /// <param name="targetString">目标字符串，用于匹配文件夹或文件名。</param>
        /// <returns>返回包含目标字符串的 JSON 文件的完整路径列表。</returns>
        List<string> FindJsonFilesWithSubstring(string rootPath, string targetString)
        {
            List<string> jsonFiles = new List<string>();

            try
            {
                // 获取当前路径下的所有文件夹
                foreach (string dir in Directory.GetDirectories(rootPath))
                {
                    // 检查文件夹名称是否包含目标字符串
                    if (dir.Contains(targetString))
                    {
                        // 查找文件夹内包含目标字符串的 JSON 文件
                        foreach (string file in Directory.GetFiles(dir, "*.json"))
                        {
                            if (file.Contains(targetString))
                            {
                                jsonFiles.Add(file);  // 添加完整路径
                            }
                        }
                    }
                    // 递归搜索子文件夹
                    jsonFiles.AddRange(FindJsonFilesWithSubstring(dir, targetString));
                }
            }
            catch (UnauthorizedAccessException) // 处理权限不足的异常
            {
                Tools.ProduceLogTextError("没有权限访问路径：" + rootPath);
            }
            return jsonFiles;
        }
        #endregion
    }
}
